import OpenAI from "openai";
const sendMsg = async (event, chatObj) => {
    const { chatList, apiKey, organization = undefined, proxyUrl, chatConfig } = chatObj;
    const configuration = {
        organization: organization,
        apiKey: apiKey,
        timeout: 5 * 1000,
        baseURL: proxyUrl ?? `https://api.openai.com/v1`
    }
    const openai = new OpenAI(configuration);
    // const list = await openai.models.list();
    // console.log(list.data);
    const stream = await openai.chat.completions.create({
        model: chatConfig.model ?? 'gpt-3.5-turbo',
        max_tokens: chatConfig.max_tokens ?? 1024,
        temperature: chatConfig.temperature ?? 0.6,
        top_p: chatConfig.top_p ?? 1,
        presence_penalty: chatConfig.presence_penalty ?? 0,
        frequency_penalty: chatConfig.frequency_penalty ?? 0,
        stream: true,
        messages: chatList,
    }).catch((err) => {
        console.log('error: ' + err.error.message);
        throw new Error(err.error.message);
    })
    const eventHandler = event
    for await (const part of stream) {
        if (global.isInterrupted) {
            stream.controller.abort()
            global.isInterrupted = false;
            console.debug("--Abort--");
            break;
        }
        // console.log(part.choices[0].delta);
        eventHandler.sender.send('message-res', part.choices[0].delta);
    }
    console.debug("--Success--");

};

export { sendMsg };